package org.newcih.util;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 文件工具类
 *
 * @author newcih
 * @version 2018-01-29
 */
public class FileUtils {

    private final static Logger logger = Logger.getLogger(FileUtils.class.getName());

    /**
     * 创建或更新font_properties文件
     *
     * @param outputFolder
     * @param fileName
     * @param font
     */
    public static void updateFontProperties(File outputFolder, String fileName, Font font) {
        int    index        = fileName.indexOf(".");
        File   fontpropFile = new File(outputFolder, fileName.substring(0, index) + ".font_properties");
        String fontName     = fileName.substring(index + 1, fileName.lastIndexOf(".exp"));

        try {
            if (fontpropFile.exists()) {
                List<String> lines = Files.readAllLines(Paths.get(fontpropFile.getPath()), Charset.defaultCharset());
                for (String str : lines) {
                    if (str.startsWith(fontName + " ")) {
                        // 字体入口已存在，忽略
                        return;
                    }
                }
            } else {
                fontpropFile.getParentFile().mkdirs();
                fontpropFile.createNewFile();
            }

            String entry = String.format("%s %s %s %s %s %s\n", fontName, font.isItalic() ? "1" : "0",
                                         font.isBold() ? "1" : "0", "0", "0", "0");
            Files.write(Paths.get(fontpropFile.getPath()), entry.getBytes(), StandardOpenOption.APPEND);
        } catch (IOException e) {
            e.printStackTrace();
            logger.log(Level.WARNING, e.getMessage(), e);
        }
    }

    /**
     * 创建空文件
     *
     * @param file
     * @return
     */
    public static boolean createFile(File file) {
        try {
            return file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 创建空目录
     *
     * @param folderName 目录名
     * @return
     */
    public static File createFolder(String folderName) {
        File folder = null;
        try {
            if (folderName.endsWith(File.separator)) {
                folder = new File(folderName);
                folder.mkdirs();
            } else {
                folderName = folderName + File.separator;
                folder = new File(folderName);
                folder.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return folder;
        }

        return folder;
    }

    public static File getBaseDir(Object aType) {
        URL  dir   = aType.getClass().getResource("/" + aType.getClass().getName().replaceAll("\\.", "/") + ".class");
        File dbDir = new File(System.getProperty("user.dir"));

        try {
            if (dir.toString().startsWith("jar:")) {
                dir = new URL(dir.toString().replaceFirst("^jar:", "").replaceFirst("/[^/]+.jar!.*$", ""));
                dbDir = new File(dir.toURI());
            }
        } catch (MalformedURLException | URISyntaxException e) {
            logger.log(Level.WARNING, e.getMessage(), e);
        }
        return dbDir;
    }

    /**
     * 合并路径(处理参数中开头或结尾带有/和不带有/的路径)
     *
     * @param path
     * @return 末端带有/的路径名
     */
    public static String composePath(String... path) {
        if (path == null || path.length == 0) {
            return "";
        }

        StringBuilder pathBuilder = new StringBuilder(100);
        for (int i = 0; i < path.length; i++) {
            // 首路径的开头/表示根路径，不用移除，之后参数的开头/可移除
            if (path[i].startsWith(File.separator) && i != 0) {
                path[i] = path[i].substring(1, path[i].length());
            }

            if (path[i].endsWith(File.separator)) {
                pathBuilder.append(path[i]);
            } else {
                pathBuilder.append(path[i]).append(File.separator);
            }
        }

        return pathBuilder.toString();
    }

    /**
     * 读取UTF-8编码的文本文件
     *
     * @param textFile
     * @return
     * @throws Exception
     */
    public static String readTextFile(File textFile) throws Exception {
        return new String(Files.readAllBytes(textFile.toPath()), StandardCharsets.UTF_8);
    }

    /**
     * 写入UTF-8编码的文本文件
     *
     * @param textFile
     * @param str
     * @throws Exception
     */
    public static void writeTextFile(File textFile, String str) throws Exception {
        Files.write(textFile.toPath(), str.getBytes(StandardCharsets.UTF_8), StandardOpenOption.TRUNCATE_EXISTING);
    }

    /**
     * 清除空box文件
     *
     * @param boxFile
     */
    public static void removeEmptyBoxes(File boxFile) {
        try {
            writeTextFile(boxFile, readTextFile(boxFile).replaceAll("(?m)^\\s+.*\n", ""));
        } catch (Exception e) {
            logger.log(Level.WARNING, e.getMessage(), e);
        }
    }

    public static void main(String[] args) throws Exception {

    }
}
